
package com.xebest.web.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.xebest.api.dto.WeChatVenCarListPageDTO;
import com.xebest.common.base.pagedto.XePageInfoDto;
import com.xebest.common.util.HttpClientUtil;
import com.xebest.common.util.XeBaseUtil;
import com.xebest.config.SmsConfig;
import com.xebest.constant.XeConstans;
import com.xebest.constant.XeSmsConstans;
import com.xebest.util.SmsConstants;
import com.xebest.web.form.XeVenOrderLogisticsForm;
import com.xebest.web.mapper.read.WeChatVenOrderLogisticsReadMapper;
import com.xebest.web.mapper.read.XeLogisticsCarReadMapper;
import com.xebest.web.mapper.write.XeVenOrderLogisticsWriteMapper;
import com.xebest.web.model.XeVenCarEntity;
import com.xebest.web.model.XeVenCarLinesEntity;
import com.xebest.web.service.WeChatVenOrderLogisticsService;
import com.xebest.web.service.XeVenOrderLogisticsService;
import com.xebest.web.view.XeVenOrderLogisticsView;

@Service
public class WeChatVenOrderLogisticsServiceImpl implements WeChatVenOrderLogisticsService {

	@Autowired
	private WeChatVenOrderLogisticsReadMapper logisticsReadMapper;

	@Autowired
	private XeLogisticsCarReadMapper xeLogisticsCarReadMapper;

	@Autowired
	private XeVenOrderLogisticsWriteMapper xeVenOrderLogisticsWriteMapper;

	@Autowired
	private XeVenOrderLogisticsService logisticsService;

	@Autowired
	private SmsConfig smsConfig;

	private static final Logger log = LoggerFactory.getLogger(WeChatVenOrderLogisticsServiceImpl.class);// 日志记录类

	/**
	 * 物流单查询
	 */
	@Override
	public List<XeVenOrderLogisticsView> queryOrderLogisticsList(XeVenOrderLogisticsForm form) {

		List<XeVenOrderLogisticsView> logisticsViews = logisticsReadMapper.queryOrderLogisticsList(form);
		for (XeVenOrderLogisticsView logisticsView : logisticsViews) {
			if (!StringUtils.isEmpty(logisticsView.getCaAreaId())) {
				String area = XeBaseUtil.baseUtil.getOrgAreaName(Integer.parseInt(logisticsView.getCaAreaId()));
				logisticsView.setReceiptArea(area + "-" + logisticsView.getCaStreet());
			}
			// xvoi.order_status IN(3,6) AND xvsi.tms_status=1 AND
			// xvoi.ship_type IN(1,2)
			if ((logisticsView.getOrderStatus() == 3 || logisticsView.getOrderStatus() == 6)
					&& logisticsView.getTmsStatus() == 1
					&& (logisticsView.getShipType() == 1 || logisticsView.getShipType() == 2)) {
				logisticsView.setViewFlag(1);
			} else {
				logisticsView.setViewFlag(2);
			}
			// 如果订单状态是已发货，派车装为未派车，则不显示状态
			if ((logisticsView.getOrderStatus() == 2 && logisticsView.getCarSendStatus() == 1)
					|| logisticsView.getShipType() == 3) {
				logisticsView.setCarSendStatus(0);
			}

		}
		return logisticsViews;

	}

	/**
	 * 物流派车列表查询
	 */
	@Override
	public List<XeVenOrderLogisticsView> querySendCarList(XeVenOrderLogisticsForm form) {
		List<XeVenOrderLogisticsView> loList = logisticsReadMapper.querySendCarList(form);
		for (XeVenOrderLogisticsView logisticsView : loList) {
			if (!StringUtils.isEmpty(logisticsView.getAreaId()) && !StringUtils.isEmpty(logisticsView.getCaAreaId())) {
				String area = XeBaseUtil.baseUtil.getOrgAreaName(Integer.parseInt(logisticsView.getAreaId()));
				logisticsView.setStoreArea(area);
				String rearea = XeBaseUtil.baseUtil.getOrgAreaName(Integer.parseInt(logisticsView.getCaAreaId()));
				logisticsView.setReceiptArea(rearea + "-" + logisticsView.getCaStreet());
			}
		}
		return loList;

	}

	/**
	 * 查询车辆列表
	 */
	@Override
	public List<Map<String, Object>> queryCarList(XeVenOrderLogisticsForm form) {

		List<Map<String, Object>> carList = logisticsReadMapper.queryCarList(form);
		for (Map<String, Object> car : carList) {
			StringBuffer routeStr = new StringBuffer("");
			String starAreas = car.get("startAreaIds") + "";
			String endAreas = car.get("endAreaIds") + "";
			car.put("address", "");
			if (!StringUtils.isEmpty(starAreas) && !StringUtils.isEmpty(endAreas)) {
				String[] starAreaArr = starAreas.split("_");
				String[] endAreaArr = endAreas.split("_");
				for (int i = 0; i < starAreaArr.length; i++) {
					String starArea = XeBaseUtil.baseUtil.getOrgAreaName(Integer.parseInt(starAreaArr[i]));
					String endArea = XeBaseUtil.baseUtil.getOrgAreaName(Integer.parseInt(endAreaArr[i]));
					routeStr.append(starArea);
					routeStr.append("——");
					routeStr.append(endArea);
					routeStr.append("；");
				}
				car.put("address", routeStr);
			}
		}
		return carList;

	}

	/**
	 * 查询所有车辆
	 */
	@Override
	public List<Map<String, Object>> queryAllCarList(XeVenOrderLogisticsForm form) {
		List<Map<String, Object>> carList = logisticsReadMapper.queryAllCarList(form);
		for (Map<String, Object> car : carList) {
			StringBuffer routeStr = new StringBuffer("");
			String starAreas = car.get("startAreaIds") + "";
			String endAreas = car.get("endAreaIds") + "";
			car.put("address", "");
			if (!StringUtils.isEmpty(starAreas) && !StringUtils.isEmpty(endAreas)) {
				String[] starAreaArr = starAreas.split("_");
				String[] endAreaArr = endAreas.split("_");
				for (int i = 0; i < starAreaArr.length; i++) {
					String starArea = XeBaseUtil.baseUtil.getOrgAreaName(Integer.parseInt(starAreaArr[i]));
					String endArea = XeBaseUtil.baseUtil.getOrgAreaName(Integer.parseInt(endAreaArr[i]));
					routeStr.append(starArea);
					routeStr.append("——");
					routeStr.append(endArea);
					routeStr.append("；");
				}
				car.put("address", routeStr);
			}
		}
		return carList;

	}

	/**
	 * 物流车辆管理列表
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public WeChatVenCarListPageDTO queryErpLogisticsCarList(XeVenOrderLogisticsForm form, int pageNum, int pageSize) {

		XeVenCarEntity xeVenCarEntity = new XeVenCarEntity();
		xeVenCarEntity.setUserCode(form.getUserCode());

		List<XeVenCarEntity> carList = new ArrayList<>();
		String userCode = form.getUserCode();
		List<String> carIds = xeLogisticsCarReadMapper.queryCarIdByUserCode(xeVenCarEntity);
		// 分页查询
		PageHelper.startPage(pageNum, pageSize);
		if (carIds != null && carIds.size() > 0) {
			carList = logisticsReadMapper.queryErpLogisticsCarList(carIds, form);
			// 区分是否是供应商本身的车辆
			for (int i = 0; i < carList.size(); i++) {
				if (userCode.equals(carList.get(i).getUserCode())) {
					carList.get(i).setIsVenSelf(1);
				} else {
					carList.get(i).setIsVenSelf(2);
				}
				List<XeVenCarLinesEntity> listLine = xeLogisticsCarReadMapper
						.queryCarLinesByCarId(carList.get(i).getCarId());
				for (XeVenCarLinesEntity carLine : listLine) {
					carLine.setStartProvinceName(XeBaseUtil.baseUtil.getAreaName(carLine.getStartProvinceId()));
					carLine.setStartCityName(XeBaseUtil.baseUtil.getAreaName(carLine.getStartCityId()));
					carLine.setStartAreaName(XeBaseUtil.baseUtil.getAreaName(carLine.getStartAreaId()));
					carLine.setEndProvinceName(XeBaseUtil.baseUtil.getAreaName(carLine.getEndProvinceId()));
					carLine.setEndCityName(XeBaseUtil.baseUtil.getAreaName(carLine.getEndCityId()));
					carLine.setEndAreaName(XeBaseUtil.baseUtil.getAreaName(carLine.getEndAreaId()));
				}
				carList.get(i).setListLine(listLine);
			}
		}

		WeChatVenCarListPageDTO resultDto = new WeChatVenCarListPageDTO();

		XePageInfoDto<XeVenCarEntity> pageInfo = new XePageInfoDto<XeVenCarEntity>(carList);

		resultDto.setXePageInfoDto(pageInfo);
		resultDto.setList(carList);

		return resultDto;
	}

	/**
	 * 确认接货
	 */
	@Override
	public void confirmDelivery(String logtsCode) {

		xeVenOrderLogisticsWriteMapper.confirmDelivery(logtsCode);

	}

	/**
	 * 查询标准重量
	 */
	@Override
	public BigDecimal queryNormWeightByParam(Map<String, String> paramMap) {

		// 标准重量合计
		BigDecimal totalNormWeigh = new BigDecimal(0);

		List<Map<String, Object>> resultList = logisticsReadMapper.queryNormWeightByParam(paramMap);

		if (resultList != null && resultList.size() != 0) {
			for (Map<String, Object> map : resultList) {
				BigDecimal normWeight = (BigDecimal) map.get("normWeight");
				BigDecimal purchaseNum = (BigDecimal) map.get("purchaseNum");
				BigDecimal realSendNum = (BigDecimal) map.get("realSendNum");

				if (purchaseNum != null && normWeight != null) {

					if (realSendNum != null) {
						// 有确认实发
						if (purchaseNum.compareTo(realSendNum) != XeConstans._XE_ZERO) {
							normWeight = (normWeight.divide(purchaseNum, 2, RoundingMode.HALF_UP))
									.multiply(realSendNum);
							totalNormWeigh = totalNormWeigh.add(normWeight);
						} else {
							// 没有确认实发 ---累加
							totalNormWeigh = totalNormWeigh.add(normWeight);
						}

					} else {
						// 没有确认实发 ---累加
						totalNormWeigh = totalNormWeigh.add(normWeight);
						System.out.println(totalNormWeigh);
					}
				}

			}

		}

		return totalNormWeigh;
	}

	/**
	 * 查询shopName
	 */
	@Override
	public String queryShopNameByOrderId(String orderId) {

		String shopName = logisticsReadMapper.queryShopNameByOrderId(orderId);

		return shopName;
	}

	/**
	 * 派车向司机发短信
	 * 
	 * @param logtsCode
	 *            物流单号
	 * @param orderId
	 *            订单号
	 * @param userCode
	 *            用户Code
	 * @param mobilePhone
	 *            司机电话
	 * @author ysl
	 * @throws Exception
	 */
	public void sendMsgToDriver(String logtsCode, String orderId, String userCode, String mobilePhone)
			throws Exception {

		// 向司机发送短信通知
		XeVenOrderLogisticsForm paramForm = new XeVenOrderLogisticsForm();
		paramForm.setLogtsCode(logtsCode);
		Map<String, Object> sendCarLogistics = logisticsService.querySendCarLogisticsByLogtsCode(paramForm);

		// 收货地址
		String receiptAddress = null;
		// 收货人电话
		String caPhone = null;

		if (sendCarLogistics != null) {
			if (sendCarLogistics.get("receiptAddress") != null) {
				receiptAddress = (String) sendCarLogistics.get("receiptAddress");
			}
			caPhone = (String) sendCarLogistics.get("caPhone");
		}
		// 查询商品标准重量
		Map<String, String> paramMap = new HashMap<>();
		paramMap.put("orderId", orderId);
		paramMap.put("userCode", userCode);
		BigDecimal totalNormWeigh = this.queryNormWeightByParam(paramMap);
		totalNormWeigh = totalNormWeigh.setScale(2, BigDecimal.ROUND_HALF_UP);
		// 查询商家店铺名称
		String shopName = this.queryShopNameByOrderId(orderId);

		StringBuffer sb1 = new StringBuffer();
		sb1.append("mobileNO=").append(mobilePhone).append("&merchantKey=").append(smsConfig.getMerchantKey());
		String verifyString1 = XeBaseUtil.baseUtil.getKeyedDigest(sb1.toString(), SmsConstants.MSG_MERCHANT_KEY);
		JSONObject smsJsonData = new JSONObject();
		smsJsonData.put("mobileNO", mobilePhone);
		smsJsonData.put("sendSource", "派车操作--向司机发送短信");
		smsJsonData.put("smsNO", XeSmsConstans.XE_ERP_SENDCAR_DRIVER_SEND_MSG);
		smsJsonData.put("verifyString", verifyString1);
		smsJsonData.put("dealNo", logtsCode);
		smsJsonData.put("receiptAddress", receiptAddress);
		smsJsonData.put("caPhone", caPhone);
		smsJsonData.put("totalNormWeigh", totalNormWeigh);
		smsJsonData.put("shopName", shopName);

		log.info("派车成功向司机发送短信通知信参数：--->" + JSON.toJSONString(smsJsonData));
		String postJSON = HttpClientUtil.postJSON(smsConfig.getSmsUrl(), smsJsonData);
		log.info("派车成功向司机发送短信---ysl---endReturn--：--->" + postJSON);

	}

}
